package ext.tianma.doc.util;

import java.io.IOException;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ext.com.iba.IBAUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.tianma.bom.util.QueryUtil;
import ext.tianma.bom.workflow.BOMBusinessUtil;
import wt.content.ContentHolder;
import wt.doc.WTDocument;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.httpgw.URLFactory;
import wt.inf.container.WTContainer;
import wt.lifecycle.LifeCycleHelper;
import wt.lifecycle.LifeCycleHistory;
import wt.lifecycle.LifeCycleManaged;
import wt.lifecycle.State;
import wt.org.WTUser;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.pom.PersistenceException;
import wt.query.KeywordExpression;
import wt.query.OrderBy;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.ClientTypedUtility;
import wt.type.TypeDefinitionForeignKey;
import wt.type.TypeDefinitionReference;
import wt.type.Typed;
import wt.util.WTException;
import wt.util.WTStandardDateFormat;
import wt.vc.Iterated;
import wt.vc.VersionReference;

public class DCCInquireStatementHelp{
	private static Locale LOCALE = Locale.CHINA;
	public static final String  productType  = "productType"; //型号
	public static final String  ModulesDevelopedLand  = "modulesDevelopedLand";//研发地
	public static final String  ModuleOrigin  = "moduleOrigin";//生产地
	public static final String  DocVersion  = "cn.tianma.docVersion";//版本号
	public static final String ATTRIBUTE_NAME = "SmallDocType";//文档小类
	public static final String ProcessDocuments = "cn.tianma.ProcessDocuments";//工艺文件
	public static final String ControlDocument = "cn.tianma.ControlDocument";//受控PDF图纸
	public static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	public static final String discardState = "OBSOLESCENCE";//废弃状态
	
	/**
	 * 根据组合条件高级查询文档
	 * 
	 * @param docType 工艺文件文档小类
	 * @param repository 产品库
	 * @param docName  文档名称
	 * @param startdate  开始时间
	 * @param enddate  结束时间
	 * @param modulesDevelopedLand 研发地
	 * @param moduleOrigin 生产地
	 * @param controlDocumentNum  受控PDF图纸
	 * @param states 图纸状态
	 * @return
	 * @throws WTException
	 */
	public static List<WTDocument> getDocByTypeAndRepository(String docType, String repository, String docName, String startdate, String enddate, String modulesDevelopedLand, String moduleOrigin, String controlDocumentNum, String states) throws WTException{
		
		
		List<WTDocument> result = new ArrayList<WTDocument>();
		QuerySpec qs = new QuerySpec();
	    int docIndex = qs.appendClassList(WTDocument.class, true);
	    qs.setAdvancedQueryEnabled(true);
		try {
			if(states != null && !states.equals("")) {//当文档状态不为空
				List<String> stateList = new ArrayList<String>();
				String[] state = states.split(";");
				for (int i = 0; i < state.length;i++){
					stateList.add(state[i]);
		        }
				for(int j =0; j<stateList.size(); j++) {
					states = stateList.get(j);
					if(stateList.size()>1) {//当文档状态大于一个
						if(0==j) {
					        qs.appendOpenParen();//左括号
					        SearchCondition scState = new SearchCondition(WTDocument.class,WTDocument.LIFE_CYCLE_STATE,SearchCondition.EQUAL,states);
							qs.appendWhere(scState,new int[]{0});
							qs.appendOr();//或者
						}else if((stateList.size()-1)==j) {
							SearchCondition scState = new SearchCondition(WTDocument.class,WTDocument.LIFE_CYCLE_STATE,SearchCondition.EQUAL,states);
							qs.appendWhere(scState,new int[]{0});
							qs.appendCloseParen();//右括号
						}else {
							SearchCondition scState = new SearchCondition(WTDocument.class,WTDocument.LIFE_CYCLE_STATE,SearchCondition.EQUAL,states);
							qs.appendWhere(scState,new int[]{0});
							qs.appendOr();
						}
					}else {//当文档状态等于一个
				        SearchCondition scState = new SearchCondition(WTDocument.class,WTDocument.LIFE_CYCLE_STATE,SearchCondition.EQUAL,states);
						qs.appendWhere(scState,new int[]{0});
					}
		        }
			}else {//当文档状态为空
				SearchCondition scState = new SearchCondition(WTDocument.class,WTDocument.LIFE_CYCLE_STATE,SearchCondition.NOT_EQUAL,discardState);
				qs.appendWhere(scState,new int[]{0});
			}
			
			if(docType != null && !docType.equals("")) {//当文档小类不为空
				List<String> docTypeList = new ArrayList<String>();
				String[] docTypes = docType.split(";");
				for (int i = 0; i < docTypes.length;i++){
					docTypeList.add(docTypes[i]);
		        }
				for(int j =0; j<docTypeList.size(); j++) {
		        	docType = docTypeList.get(j);
		        	if(docTypeList.size()>1) {//当文档小类大于一个
		        		if(0==j) {
							qs.appendAnd();
					        TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(ProcessDocuments);//查询工艺文件
							SearchCondition scOther = new SearchCondition(WTDocument.class,
									Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
											+ TypeDefinitionForeignKey.BRANCH_ID,
									SearchCondition.EQUAL, clientType.getKey().getBranchId());
							qs.appendWhere(scOther,new int[]{0});
							
							qs.appendAnd();
							qs.appendOpenParen();//左括号
					        qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ATTRIBUTE_NAME, docType, SearchCondition.EQUAL),
									new int[] { 0 });
							qs.appendOr();//或者
						}else if((docTypeList.size()-1)==j) {
							qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ATTRIBUTE_NAME, docType, SearchCondition.EQUAL),
									new int[] { 0 });
							qs.appendCloseParen();//右括号
						}else {
							qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ATTRIBUTE_NAME, docType, SearchCondition.EQUAL),
									new int[] { 0 });
							qs.appendOr();
						}	
		        	}else {//当文档小类等于一个
		        		qs.appendAnd();
				        TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(ProcessDocuments);//查询工艺文件的文档小类
						SearchCondition scOther = new SearchCondition(WTDocument.class,
								Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
										+ TypeDefinitionForeignKey.BRANCH_ID,
								SearchCondition.EQUAL, clientType.getKey().getBranchId());
						qs.appendWhere(scOther,new int[]{0});
						
						qs.appendAnd();
				        qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ATTRIBUTE_NAME, docType, SearchCondition.EQUAL),
								new int[] { 0 });
		        	}
		        }
			}
			
			if(controlDocumentNum != null && !controlDocumentNum.equals("")){//当受控图纸编号不为空
				List<String> controlList = new ArrayList<String>();
				String[] control = controlDocumentNum.split(";");
				for (int i = 0; i < control.length;i++){
					controlList.add(control[i]);
		        }
				for(int j =0; j<controlList.size(); j++) {
					controlDocumentNum = controlList.get(j);
					if(controlList.size()>1) {
						if(0==j) {
			        		qs.appendAnd();
					        TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(ControlDocument);//查询受控PDF图纸
							SearchCondition scOther = new SearchCondition(WTDocument.class,
									Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
											+ TypeDefinitionForeignKey.BRANCH_ID,
									SearchCondition.EQUAL, clientType.getKey().getBranchId());
							qs.appendWhere(scOther,new int[]{0});
							
							qs.appendAnd();
					        qs.appendOpenParen();//左括号
					        SearchCondition scDocNumber = new SearchCondition(WTDocument.class,WTDocument.NAME,SearchCondition.LIKE,controlDocumentNum+"%");
							qs.appendWhere(scDocNumber,new int[]{0});
							qs.appendOr();//或者
						}else if((controlList.size()-1)==j) {
							SearchCondition scDocNumber = new SearchCondition(WTDocument.class,WTDocument.NAME,SearchCondition.LIKE,controlDocumentNum+"%");
							qs.appendWhere(scDocNumber,new int[]{0});
							qs.appendCloseParen();//右括号
						}else {
							SearchCondition scDocNumber = new SearchCondition(WTDocument.class,WTDocument.NAME,SearchCondition.LIKE,controlDocumentNum+"%");
							qs.appendWhere(scDocNumber,new int[]{0});
							qs.appendOr();
						}
					}else {
						qs.appendAnd();
				        TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(ControlDocument);//查询受控PDF图纸
						SearchCondition scOther = new SearchCondition(WTDocument.class,
								Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
										+ TypeDefinitionForeignKey.BRANCH_ID,
								SearchCondition.EQUAL, clientType.getKey().getBranchId());
						qs.appendWhere(scOther,new int[]{0});
						
						qs.appendAnd();
				        SearchCondition scDocNumber = new SearchCondition(WTDocument.class,WTDocument.NAME,SearchCondition.LIKE,controlDocumentNum+"%");
						qs.appendWhere(scDocNumber,new int[]{0});
					}
		        }
			}
			
			if((docType == null || docType.equals("")) && (controlDocumentNum == null || controlDocumentNum.equals(""))){//文档类型和受控图纸编号都为空
				TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(ProcessDocuments);//工艺文件
				qs.appendAnd();
		        qs.appendOpenParen();//左括号
				SearchCondition sc = new SearchCondition(WTDocument.class,
						Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
								+ TypeDefinitionForeignKey.BRANCH_ID,
						SearchCondition.EQUAL, clientType.getKey().getBranchId());
				qs.appendWhere(sc,new int[]{0});
				qs.appendOr();//或者
				TypeDefinitionReference clientType1 = ClientTypedUtility.getTypeDefinitionReference(ControlDocument);//受控PDF图纸
				SearchCondition scOther = new SearchCondition(WTDocument.class,
						Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
								+ TypeDefinitionForeignKey.BRANCH_ID,
						SearchCondition.EQUAL, clientType1.getKey().getBranchId());
				qs.appendWhere(scOther,new int[]{0});
				qs.appendCloseParen();//右括号
			}
			
			if(docName != null && !docName.equals("")) {//文档名称不为空，模糊查询
				SearchCondition scDocName = new SearchCondition(WTDocument.class,WTDocument.NAME,SearchCondition.LIKE,"%"+docName+"%");
        		qs.appendAnd();
            	qs.appendWhere(scDocName,new int[]{0});
			}
			
			if(startdate != null && !startdate.equals("")) {//开始时间不为空
				Date startDate = dateFormat.parse(startdate);
				SearchCondition scStartDate = new SearchCondition(WTDocument.class,WTDocument.MODIFY_TIMESTAMP,SearchCondition.GREATER_THAN_OR_EQUAL,new Timestamp(startDate.getTime()));
        		qs.appendAnd();
            	qs.appendWhere(scStartDate,new int[]{0});
        	}
			
			if(enddate != null && !enddate.equals("")) {//结束时间不为空
				
				Date endDate = dateFormat.parse(enddate);
				SearchCondition scEndDate = new SearchCondition(WTDocument.class,WTDocument.MODIFY_TIMESTAMP,SearchCondition.LESS_THAN_OR_EQUAL,new Timestamp(endDate.getTime()));
				qs.appendAnd();
	        	qs.appendWhere(scEndDate,new int[]{0});//结束时间
			}
			
			if(repository != null && !repository.equals("")) {//产品库不为空
				List<String> repositoryList = new ArrayList<String>();
				String[] repositorys = repository.split(";");
				for (int i = 0; i < repositorys.length;i++){
					repositoryList.add(repositorys[i]);
		        }
				for(int j =0; j<repositoryList.size(); j++) {
					repository = repositoryList.get(j);
					WTContainer container = getContainer(repository);
	    			long containerID = PersistenceHelper.getObjectIdentifier(container).getId();
	    			if(repositoryList.size()>1) {//产品库个数大于一个
	    				if(0==j) {
							qs.appendAnd();
					        qs.appendOpenParen();//左括号
					        SearchCondition containerReference = new SearchCondition(WTDocument.class,"containerReference.key.id", SearchCondition.EQUAL,containerID);
					        qs.appendWhere(containerReference,new int[]{0});
							qs.appendOr();//或者
						}else if((repositoryList.size()-1)==j) {
							SearchCondition containerReference = new SearchCondition(WTDocument.class,"containerReference.key.id", SearchCondition.EQUAL,containerID);
							qs.appendWhere(containerReference,new int[]{0});
							qs.appendCloseParen();//右括号
						}else {
							SearchCondition containerReference = new SearchCondition(WTDocument.class,"containerReference.key.id", SearchCondition.EQUAL,containerID);
			            	qs.appendWhere(containerReference,new int[]{0});
							qs.appendOr();
						}
	    			}else {//产品库等于一个
	    				qs.appendAnd();
				        SearchCondition containerReference = new SearchCondition(WTDocument.class,"containerReference.key.id", SearchCondition.EQUAL,containerID);
				        qs.appendWhere(containerReference,new int[]{0});
	    			}
		        }
        	}
			
			if(modulesDevelopedLand != null && !modulesDevelopedLand.equals("")) {//研发地不为空
				qs.appendAnd();
				qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ModulesDevelopedLand, modulesDevelopedLand, SearchCondition.EQUAL),
						new int[] { 0 });
				
        	}
			
			if(moduleOrigin != null && !moduleOrigin.equals("")) {//生产地不为空
				List<String> moduleOriginList = new ArrayList<String>();
				String[] moduleOrigins = moduleOrigin.split(";");
				for (int i = 0; i < moduleOrigins.length;i++){
					moduleOriginList.add(moduleOrigins[i]);
		        }
				for(int j =0; j<moduleOriginList.size(); j++) {
					moduleOrigin = moduleOriginList.get(j);
					if(moduleOriginList.size()>1) {//生产地个数大于一个
						if(0==j) {
							qs.appendAnd();
					        qs.appendOpenParen();//左括号
					        qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ModuleOrigin, moduleOrigin, SearchCondition.EQUAL),
									new int[] { 0 });
							qs.appendOr();//或者
						}else if((moduleOriginList.size()-1)==j) {
							qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ModuleOrigin, moduleOrigin, SearchCondition.EQUAL),
									new int[] { 0 });
							qs.appendCloseParen();//右括号
						}else {
							qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ModuleOrigin, moduleOrigin, SearchCondition.EQUAL),
									new int[] { 0 });
							qs.appendOr();
						}
					}else {//生产地个数等于一个
						qs.appendAnd();
				        qs.appendWhere(QueryUtil.getIBASearchCondition(WTDocument.class, ModuleOrigin, moduleOrigin, SearchCondition.EQUAL),
								new int[] { 0 });
					}
		        }
        	}
    	    qs.appendAnd();
    	    qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"),
    	        SearchCondition.EQUAL, new KeywordExpression("1")));
    	    qs.appendOrderBy(new OrderBy(new KeywordExpression("A0.MODIFYSTAMPA2"), false));
    	    //System.out.println("----------sql---------"+qs.toString());
    	    QueryResult qr = PersistenceHelper.manager.find(qs);
    	    while(qr.hasMoreElements()){
    	      Object obj[] = (Object[])qr.nextElement();
    	      if(obj[0] instanceof WTDocument){
					WTDocument doc = (WTDocument) obj[0];
					result.add(doc);
				}
    	    }
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 获得DCC查询报表字段
	 * 
	 * @param ob
	 * @param array
	 * @param doc
	 * @param type
	 * @param drawingType
	 * @param name
	 * @throws WTException
	 * @throws JSONException
	 * @throws IOException
	 */
	public static void saveStatement(JSONObject ob, JSONArray array, WTDocument doc, String type, String drawingType, String name)
			throws WTException, JSONException, IOException {
		
		WTPart wtPart = getPartByDoc(doc);
		String Item1 ="";
		if(wtPart != null) {
			Item1 = wtPart.getNumber();//料号
		}
		String productType1 = IBAUtil.getIBAValue(doc,productType)==null ? "": ((String) IBAUtil.getIBAValue(doc,productType));//型号
		
		String version = IBAUtil.getIBAValue(doc,DocVersion)==null ? "": ((String) IBAUtil.getIBAValue(doc,DocVersion));//版号
		
		if(!"".equals(version)) {
			version = IBAUtil.getIBAValue(doc,DocVersion)==null ? "": ((String) IBAUtil.getIBAValue(doc,DocVersion));//版号
		}else {
			if ("工艺文件".equals(drawingType)) {//设置工艺文件的版号
				String ver = name.substring(name.length()-3,name.length());
				if(ver.contains(".")) {
					version = name.substring(name.length()-3,name.length());
				}
			}
			if(Item1 !=null && !"".equals(Item1)) {//当料号不为空时，设置受控PDF图纸的版号
				if ("受控PDF图纸".equals(drawingType)) {
					version = "0" + Item1.charAt(Item1.length() - 1);
				}
			}
		}
		String folderPath = doc.getFolderPath();
		folderPath = folderPath.substring(1, folderPath.length());
		WTContainer con = doc.getContainer();//根据doc获得当前的储存库
		String conName = con.getName();//获得储存库name
		String[] folders = folderPath.split("/");
		List<String> list = new ArrayList<String>();
		for(int i=0; i<folders.length; i++) {
			list.add(folders[i]);
		}
		list.remove(0);
		list.remove(list.size()-1);
		String folder = conName;//存储位置
		for(int j =0; j<list.size(); j++) {
			String drawingName = list.get(j);
			folder = folder+"/"+drawingName;
		}
		String updateBy = CommonPDMUtil.getModifierName(doc);//拟制人
		WTUser user = getUserByName(updateBy);//根据用户名获得用户对象
		updateBy = user.getFullName();//获得用户全名
		String modulesDevelopedLand = IBAUtil.getIBAValue(doc,ModulesDevelopedLand)==null ? "": ((String) IBAUtil.getIBAValue(doc,ModulesDevelopedLand));//研发地
		String modulesDevelopedLandValue = "";
		if(modulesDevelopedLand != null && !modulesDevelopedLand.equals("")) {
			if(modulesDevelopedLand.equals("厦门")) {//处理历史数据：研发地有厦门
				modulesDevelopedLandValue = "厦门";
			}else {
				modulesDevelopedLandValue = GetResearchSite.getEnumerationDisplayValue("地区", modulesDevelopedLand);//获得研发地的显示名称
			}
		}
		String moduleOrigin1Value = "";
		Vector moduleOrigin1List = IBAUtil.getIBAValue2(doc, ModuleOrigin);
		if(moduleOrigin1List.size()>0) {
			for(int i=0 ; i< moduleOrigin1List.size(); i++) {
				String moduleOrigin1 = (String) moduleOrigin1List.get(i);
				if(moduleOrigin1.equals("厦门")) {//处理历史数据：生产地有厦门
					if(moduleOrigin1Value!="") {
						moduleOrigin1Value = moduleOrigin1Value +", " + "厦门";
					}else {
						moduleOrigin1Value = "厦门";
					}
				}else {
					if(moduleOrigin1Value !="") {
						moduleOrigin1Value = moduleOrigin1Value +", "+ GetResearchSite.getEnumerationDisplayValue("地区", moduleOrigin1);//获得生产地的显示名称
					}else {
						moduleOrigin1Value = GetResearchSite.getEnumerationDisplayValue("地区", moduleOrigin1);//获得生产地的显示名称
					}
				}
			}
		}
		String releaseTime = getReleaseDocReleasedDate(doc);//文档发布时间
		String productState = doc.getState().getState().getDisplay(LOCALE);//状态
		String docUrl = docGenerateInfoPageURL(doc);//文档详情页链接
		String partUrl = partGenerateInfoPageURL(wtPart);//部件详情页链接
		ob.put("status", "success");
		ob.put("message", "查询成功!");
		JSONObject obOthen = new JSONObject();
		obOthen.put("Item1", Item1);
		obOthen.put("productType1", productType1);
		obOthen.put("version", version);
		obOthen.put("name", name);
		obOthen.put("folder", folder);
		obOthen.put("releaseTime", releaseTime);
		obOthen.put("updateBy", updateBy);
		obOthen.put("modulesDevelopedLand1", modulesDevelopedLandValue);
		obOthen.put("moduleOrigin1", moduleOrigin1Value);
		obOthen.put("type", type);
		obOthen.put("productState", productState);
		obOthen.put("drawingType", drawingType);
		obOthen.put("partUrl", partUrl);
		obOthen.put("docUrl", docUrl);
		array.put(obOthen);
		ob.put("data", array);
	}
	/**
	 * 获得文档发布时间
	 * @param contentHolder
	 * @return
	 * @throws WTException
	 */
	public static String getReleaseDocReleasedDate(ContentHolder contentHolder) throws WTException {
        String releaseDate = "";
        if (contentHolder instanceof LifeCycleManaged) {
            LifeCycleHistory history;
            QueryResult qr = LifeCycleHelper.service.getHistory((LifeCycleManaged) contentHolder);
            while (qr.hasMoreElements()) {
                history = (LifeCycleHistory) qr.nextElement();
                if (State.RELEASED.equals(history.getState()))
                    releaseDate = WTStandardDateFormat.format(history.getCreateTimestamp(), "yyyy/MM/dd");
            }
        }
        return releaseDate;
    }
	/**
	 * 根据名称获取上下文
	 * 
	 * @param repository
	 * @return
	 * @throws QueryException
	 * @throws WTException
	 */
	public static WTContainer getContainer(String repository) throws wt.query.QueryException, wt.util.WTException {
		QuerySpec queryspec = new QuerySpec(WTContainer.class);
		queryspec.appendSearchCondition(
				new SearchCondition(WTContainer.class, WTContainer.NAME, SearchCondition.EQUAL, repository));
		QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
		WTContainer wtcontainer = null;
		while (queryresult.hasMoreElements()) {
			Object obj = queryresult.nextElement();
			if (obj instanceof WTContainer)
				wtcontainer = (WTContainer) obj;
		}
		return wtcontainer;
	}
	/**
	 * 根据文档获得说明部件
	 * @param doc
	 * @return
	 * @throws WTException
	 */
	public static WTPart getPartByDoc(WTDocument doc) throws WTException {
		WTPart part = null;
		QueryResult qr = PersistenceHelper.manager.navigate(doc, WTPartDescribeLink.DESCRIBES_ROLE,
				WTPartDescribeLink.class);
		while (qr.hasMoreElements()) {
			Object obj = qr.nextElement();
			if(obj instanceof WTPart) {
				part = (WTPart) obj;
			}else if(obj instanceof WTPartDescribeLink) {
				WTPartDescribeLink describeLink = (WTPartDescribeLink) qr.nextElement();
				part = describeLink.getDescribes();
			}
		}
		return part;
	}
	/**
	 * 根据doc得到文档信息页面url
	 * 
	 * @param doc
	 * @return
	 * @throws PersistenceException
	 * @throws WTException
	 */
	public static String docGenerateInfoPageURL(WTDocument doc) throws PersistenceException, WTException {
		String url = "";
		ReferenceFactory referenceFactory = new ReferenceFactory();
		URLFactory urlfactory = new URLFactory();
		String baseHref = urlfactory.getBaseHREF();
		if (doc != null && doc.getNumber() != null) {
			WTContainer container = doc.getContainer();
			String ufid = referenceFactory.getReferenceString(VersionReference.newVersionReference((Iterated) doc));
			String containerOid = "";
			if (container != null) {
				containerOid = referenceFactory.getReferenceString(container);
			}
			if ("".equals(containerOid)) {
				url = baseHref + "app/#ptc1/tcomp/infoPage?oid=" + ufid + "&u8=1";
			} else {
				url = baseHref + "app/#ptc1/tcomp/infoPage?ContainerOid=" + containerOid + "&oid=" + ufid + "&u8=1";
			}
		}
		return url;
	}
	/**
	 * 根据part得到部件信息页面url
	 * 
	 * @param part
	 * @return
	 * @throws PersistenceException
	 * @throws WTException
	 */
	public static String partGenerateInfoPageURL(WTPart part) throws PersistenceException, WTException {
		String url = "";
		ReferenceFactory referenceFactory = new ReferenceFactory();
		URLFactory urlfactory = new URLFactory();
		String baseHref = urlfactory.getBaseHREF();
		if (part != null && part.getNumber() != null) {
			WTContainer container = part.getContainer();
			String ufid = referenceFactory.getReferenceString(VersionReference.newVersionReference((Iterated) part));
			String containerOid = "";
			if (container != null) {
				containerOid = referenceFactory.getReferenceString(container);
			}
			if ("".equals(containerOid)) {
				url = baseHref + "app/#ptc1/tcomp/infoPage?oid=" + ufid + "&u8=1";
			} else {
				url = baseHref + "app/#ptc1/tcomp/infoPage?ContainerOid=" + containerOid + "&oid=" + ufid + "&u8=1";
			}
		}
		return url;
	}
	/**
	 * 获得文档类型下的所有子类型
	 * @param docType
	 * @return
	 */
	public static List<String> getWTDocumentType(String docType) {
		
		List<String> list = new ArrayList<String>();
		Hashtable<String, String> allSubTypeInnerFullName;
		try {
			allSubTypeInnerFullName = BOMBusinessUtil.getAllSubTypeInnerFullName(docType);
			Iterator<Entry<String, String>> iterator = allSubTypeInnerFullName.entrySet().iterator();
			while(iterator.hasNext()) {
				Entry<String,String> entry=iterator.next();	
				docType = entry.getValue();
				String[] docTypes = docType.split("\\|");
				docType = docTypes[docTypes.length-1];
				list.add(docType);
			}
		} catch (WTException e) {
			e.printStackTrace();
		}
		return list;
	}
	
	
	//根据用户名查询WTUser对象
		public static  WTUser getUserByName(String username) throws WTException{
			WTUser user = null ;
			QuerySpec qs = new QuerySpec(WTUser.class);
			SearchCondition sc = new SearchCondition(WTUser.class,WTUser.NAME,"=",username);
			qs.appendWhere(sc);
			QueryResult qr = PersistenceHelper.manager.find(qs);
			while(qr.hasMoreElements())
			{
				user = (WTUser)qr.nextElement();
			}
			return user;
		}
}
